package ping

import (
	"strings"
	"sync"

	"gitee.com/liumou_site/logger"
	"github.com/spf13/cast"
)

func (p *Ping) Batch(subnet string, start, stop int) (bool, []string, []string) {
	if start >= stop {
		logger.Warn("起点大于或等于终点,请重新设置参数")
		return false, nil, nil
	}
	var wg sync.WaitGroup
	var lock sync.Mutex
	var successIPs, failedIPs []string
	sub_ := subCheckAddress(subnet)
	if sub_ {
		for i := start; i <= stop; i++ {
			wg.Add(1)
			iStr := cast.ToString(i)
			ip := subnet + "." + iStr
			go func(ip string) {
				defer wg.Done()
				err := p.ICMP(ip, 3, false)
				lock.Lock()
				defer lock.Unlock()
				if err == nil {
					successIPs = append(successIPs, ip)
				} else {
					failedIPs = append(failedIPs, ip)
				}
			}(ip)
		}
		wg.Wait()
		return true, successIPs, failedIPs
	} else {
		logger.Warn("子网地址格式错误，请重新设置参数")
		return false, nil, nil
	}
}

func (p *Ping) pingBatchWorker(ip string, ok, failed chan int, lock *sync.Mutex, wg *sync.WaitGroup) {
	defer wg.Done()
	lock.Lock()
	defer lock.Unlock()
	err := p.ICMP(ip, 3, false)
	okS := <-ok
	failedS := <-failed
	if err == nil {
		logger.Debug("连接成功: ", ip)
		ok <- okS + 1
	} else {
		logger.Warn("连接失败: ", ip)
		failed <- failedS + 1
	}
}

func subCheckAddress(sub string) bool {
	sum := strings.Split(sub, ".")
	if len(sum) != 3 {
		logger.Error("IP子网格式错误,需要传入三组整数组成的字符串,当前仅传入: ", sum)
		return false
	}
	for index, value := range sum {
		values := cast.ToInt(value)
		if values > 255 || values < 0 {
			logger.Error("子网第[ %s ]个值不符合标准: ", index)
			return false
		}
	}
	return true
}
